import React, { useEffect, useState } from 'react';
import { Button, Card, Divider, Empty, message, Popconfirm, Steps, Upload } from 'antd';
import { CheckCircleTwoTone, ScheduleOutlined, UploadOutlined } from '@ant-design/icons';
import { selectByUserIdUsingPOST, updateUsingPOST } from '@/services/api/Employ';
import { useModel, useRequest, history } from 'umi';
import styles from './style.less';
import moment from 'moment';

const { Step } = Steps;

const ScheduleView: React.FC = () => {
  type SepsStatusProps = 'process' | 'wait' | 'finish' | 'error' | undefined;
  const [stepStatus, SetstepStatus] = useState<SepsStatusProps>('process');
  const [stepCurrent, SetstepCurrent] = useState<number>(4);

  const [visible, setVisible] = useState(false);
  const [confirmLoading, setConfirmLoading] = useState(false);
  const [btnDisabled, setbtnDisabled] = useState(false);

  const { initialState } = useModel('@@initialState');
  const { currentUser } = initialState || {};

  const { data: stepData } = useRequest(() => {
    return selectByUserIdUsingPOST({
      userId: currentUser?.id as number,
    });
  });

  // 获取当前流程进度
  const getCurrent = () => {
    const currentStep: any = stepData?.status;

    if ([0].includes(currentStep)) {
      SetstepCurrent(0);
    } else if ([1, 2, 3].includes(currentStep)) {
      SetstepCurrent(1);
    } else if ([4, 5, 6].includes(currentStep)) {
      SetstepCurrent(2);
    } else if ([7, 8].includes(currentStep)) {
      SetstepCurrent(3);
    }
  };

  // 获取当前流程状态（进行中/结束/完成）
  const getStatus = () => {
    const currentStatus: any = stepData?.status;
    if ([3, 6, 8].includes(currentStatus)) {
      SetstepStatus('error');
    } else if ([0, 2, 9].includes(currentStatus)) {
      SetstepStatus('finish');
    }
  };

  const showPopconfirm = () => {
    setVisible(true);
  };

  // 接受面试邀请
  const handleOk = async () => {
    setConfirmLoading(true);
    await updateUsingPOST({ valid: true, id: stepData?.id }).then(() => {
      setTimeout(() => {
        setVisible(false);
        setConfirmLoading(false);
        setbtnDisabled(true);
      }, 1000);
      message.success('面试接受成功，请准时到场！');
    });
  };

  // 拒绝面试邀请
  const handleCancel = async () => {
    await updateUsingPOST({ valid: false, id: stepData?.id }).then(() => {
      setTimeout(() => {
        setVisible(false);
        setbtnDisabled(true);
      }, 1000);
      message.success('操作成功！');
    });
  };

  // 上传审查附件
  const onUploadAttachment = async (file: any) => {
    console.log(file);
    if (file?.file?.status === 'done') {
      const fileUrl = file.file.response.data.fileUrl;
      await updateUsingPOST({ remark: fileUrl, id: stepData?.id });
      message.success('上传成功');
      return fileUrl;
    }
  };

  // 移除审查附件
  const onRemoveAttachment = async () => {
    message.success('移除成功');
  };

  const getUrlLast = (url: string) => {
    const index = url.lastIndexOf('/');
    return url.substring(index + 1, url.length);
  };

  useEffect(() => {
    getStatus();
    getCurrent();
  });

  return (
    <>
      <Card style={{ marginBottom: 24 }}>
        {stepData ? (
          <>
            <Steps direction={'horizontal'} status={stepStatus} current={stepCurrent}>
              <Step title="已投递" />
              <Step title="初审" />
              <Step title="面试" />
              <Step title="资格审查" />
              <Step title="入职" />
            </Steps>
            <Divider />
            <Steps current={stepCurrent} direction="vertical" status={stepStatus}>
              <Step
                title="已投递"
                description={
                  <p className={styles.pass}>
                    简历投递申请成功 <CheckCircleTwoTone twoToneColor="#52c41a" />
                  </p>
                }
              />
              <Step
                title="初审"
                description={
                  <>
                    {stepStatus === 'error' && stepCurrent === 1 ? '管理员审核未通过' : ''}
                    {stepCurrent === 1 && stepStatus === 'process' ? '管理员审核中' : ''}
                    {stepCurrent === 1 && stepStatus === 'finish' ? '审核通过' : ''}
                    {stepCurrent === (2 || 3) ? (
                      <p className={styles.pass}>
                        初审通过 <CheckCircleTwoTone twoToneColor="#52c41a" />
                      </p>
                    ) : (
                      ''
                    )}
                  </>
                }
              />
              <Step
                title="面试"
                description={
                  <>
                    {stepStatus === 'error' && stepCurrent === 2 ? '面试结果不匹配' : ''}
                    {stepCurrent === (2 || 3) ? (
                      <>
                        <div className={styles.interview}>
                          校方邀请您于
                          <a>{moment(stepData.secondTime).format('YYYY-MM-DD HH:mm')}</a>至
                          <a>浙江理工大学科技与艺术学院</a>
                          参加面试，请点击下方按钮确认是否参加面试。(仅一次机会，请慎重选择。)
                        </div>
                        <Popconfirm
                          title="请选择是否能够参加面试？"
                          visible={visible}
                          onConfirm={handleOk}
                          okButtonProps={{ loading: confirmLoading }}
                          onCancel={handleCancel}
                        >
                          <Button
                            type="primary"
                            onClick={showPopconfirm}
                            icon={<ScheduleOutlined />}
                            disabled={btnDisabled || stepData.valid !== null}
                          >
                            参加面试
                          </Button>
                        </Popconfirm>
                      </>
                    ) : (
                      <></>
                    )}
                    {stepCurrent === 3 ? (
                      <p className={styles.pass}>
                        面试通过 <CheckCircleTwoTone twoToneColor="#52c41a" />
                      </p>
                    ) : (
                      ''
                    )}
                  </>
                }
              />
              <Step
                title="资格审查"
                description={
                  <>
                    {stepCurrent === 3 ? (
                      <>
                        <div className={styles.interview}>
                          上传材料包括但不限于学历学位证明、教学经历、主要教学研究成果、代表性论著、未来工作计划等。(请合并为一个PDF文件)
                        </div>
                        <Upload
                          name="file"
                          action="http://localhost:8000/api/upload/uploadFile"
                          onChange={onUploadAttachment}
                          onRemove={onRemoveAttachment}
                          maxCount={1}
                          defaultFileList={
                            stepData?.remark
                              ? [
                                  {
                                    uid: '-1',
                                    name: getUrlLast(stepData?.remark),
                                    status: 'done',
                                    url: stepData?.remark,
                                  },
                                ]
                              : undefined
                          }
                        >
                          <Button
                            icon={<UploadOutlined />}
                            size={'middle'}
                            disabled={stepStatus !== 'process' || stepCurrent !== 3}
                          >
                            点击上传附件
                          </Button>
                        </Upload>
                      </>
                    ) : (
                      '上传材料包括但不限于学历学位证明、教学经历、主要教学研究成果、代表性论著、未来工作计划等。(请合并为一个PDF文件)'
                    )}
                  </>
                }
              />
              <Step title="入职" description="待入职" />
            </Steps>
          </>
        ) : (
          <Empty
            image="https://gw.alipayobjects.com/zos/antfincdn/ZHrcdLPrvN/empty.svg"
            imageStyle={{
              height: 60,
            }}
            description={<span>您尚未投递简历</span>}
          >
            <Button type="primary" onClick={() => history.push('/post')}>
              前去投递
            </Button>
          </Empty>
        )}
      </Card>
    </>
  );
};

export default ScheduleView;
